package com.jakx.plugin;

import com.jakx.controller.DemoController;
import com.jakx.service.DemoService;
import com.jakx.service.ExtService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

@Component
public class Pojie implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("======================pojie======================");
        String[] beans = applicationContext.getBeanDefinitionNames();
        for (String beanName : beans) {
            // 拿到bean的Class对象
            Class<?> beanType = applicationContext.getType(beanName);
            if (beanType == null) {
                continue;
            }
            // 拿到当前bean类型的所有字段
            Field[] declaredFields = beanType.getDeclaredFields();
            if(!beanName.contains("aaa") ){
                continue;
            }
            for (Field field : declaredFields) {
                // 从spring容器中拿到这个具体的bean对象
                Object bean = applicationContext.getBean(beanName);
                // 当前字段设置新的值
                try {
                    setFieldData(field, bean, applicationContext);
                    System.out.println("finished");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void setFieldData(Field field, Object bean, ApplicationContext applicationContext) throws Exception {
        ExtService extService = applicationContext.getBean("extService",ExtService.class);
        // 注意这里要设置权限为true
        field.setAccessible(true);
        Class<?> type = field.getType();
        if (type.equals(DemoService.class)) {
            field.set(bean, extService);
            System.out.println("HHHHHHHHH");
        }
    }
}
